<script lang="ts" setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type {UploadRequestOptions} from 'element-plus'
import myAxios from "@/plugins/axios";
import {ApiData} from "@/interfaces/apiResponse.ts";
import myUser from "@/composables/myUser.ts";
const {updateCurrentUser} = myUser()
const props = defineProps<{
  modelValue: string|undefined
}>();
const emit = defineEmits<{
  (e: 'update:modelValue', url: string): void
}>();
const imageUrl = ref(props.modelValue);
const handleAvatarSuccess = (
    response:Record<string, any>
) => {
  imageUrl.value = response.url;
}
const request = async (options:UploadRequestOptions)=>{
  //<input type='file' />
  const formData = new FormData();
  formData.append('file', options.file);
  //向后端发起请求
   const res = await myAxios.request<ApiData<{url:string}>>({
    url:`upload/image`,
    method:'POST',
    data:formData
  })
  await updateCurrentUser({avatar:res.data.url})
  emit('update:modelValue',res.data.url)
  return res.data;
}
</script>
<template>
  <el-upload
      class="avatar-uploader"
      action=""
      :http-request="request"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>
<style scoped>
.avatar-uploader .avatar {
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
